//
//  BaseViewController.m
//  YaDiuDiu
//
//  Created by 欧洪飞 on 2017/8/23.
//  Copyright © 2017年 jy. All rights reserved.
//

#import "BaseViewController.h"
#import "MainMoeyModel.h"
#import "MJExtension.h"
#import "HBView.h"
#import "MainViewController.h"
@interface BaseViewController ()
@property(nonatomic,strong)MainMoeyModel *model;
@property(nonatomic,strong)NSArray *modelArr;
@property(nonatomic,strong)NSTimer * timer;
@property(nonatomic,strong)HBView *hbview;
@end

@implementation BaseViewController

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

}

- (void)viewDidLoad {
    [super viewDidLoad];
//    [self loadMoneyRain];
    //适配ios
    // Do any additional setup after loading the view.
//    if (@available(ios 11.0,*)) {
//        UIScrollView.appearance.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
//        UITableView.appearance.estimatedRowHeight = 0;
//        UITableView.appearance.estimatedSectionFooterHeight = 0;
//        UITableView.appearance.estimatedSectionHeaderHeight = 0;
//        
//    }
}

-(void)setBGColor{
    self.view.backgroundColor = [UIColor whiteColor];
}

/*
 红包雨接口
 */
- (void)loadMoneyRain{
    
    [self loadHBView:0];
    
    NSString *str = [NSString stringWithFormat:@"%@890d69e502d1d37a9e84335ccefece57",[user objectForKey:@"token2"]];
    NSString *token = [LCMD5Tool md5:str];
    NSMutableDictionary *parmas = [NSMutableDictionary dictionary];
    [parmas setValue:token forKey:@"verifyToken"];
    [parmas setValue:[user objectForKey:@"userid"] forKey:@"id"];
    
    NSString *url = [NSString stringWithFormat:@"%@/App/Voucher/time",urlHead];
    [[AFHTTPSessionManager manager] POST:url parameters:parmas success:^(NSURLSessionDataTask *task, id responseObject) {
        
        NSInteger error = [[responseObject objectForKey:@"error"] integerValue];
        NSDictionary *dataDic = [responseObject objectForKey:@"result"];
        NSLog(@"红包雨-------%@--",dataDic);
        
        if (error == 200) {

//            [self.hbview loadHongBaoUserData:responseObject];
            [self.hbview loadHongBaoUserTiQianData:responseObject Tiqian:1];
            
            self.modelArr = [MainMoeyModel mj_objectArrayWithKeyValuesArray:dataDic[@"time"]];
            //-1: 正在开始 0:结束 other：即将开始
            for (int i = 0 ; i < self.modelArr.count; i++) {
               
                self.model = self.modelArr[i];
                if ([self.model.starttime isEqualToString:@"-1"]) {
                    
                    NSLog(@"有正在下的红包雨.....");
                    
                    
                    break;
                }else if ([self.model.starttime isEqualToString:@"0"]){
                    
                    continue;
                }else if ([self.model.starttime longLongValue]>0)
                {
                    NSLog(@"----即将下雨--");
                    [self jk_startTime:[self.model.starttime longLongValue]];
                    break;
                }
                
            }
            
        }
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"error:%@",error);
    }];
}
/*
 设置定时器
 */
-(void)jk_startTime:(long long)timeout{
    
    __block NSInteger timeOut=timeout; //倒计时时间
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
  dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(_timer, ^{
        if(timeOut<=0){ //倒计时结束，关闭
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
               
                
            });
        }else{
          
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
               
                NSLog(@"等待红包雨出现-----%ld---%@",(long)timeOut,[self lessSecondToDay:timeOut]);
            });
            timeOut--;
            
        }
    });
    dispatch_resume(_timer);
    
}

//根据秒数计算剩余时间：天，小时，分钟，秒
- (NSString *)lessSecondToDay:(NSUInteger)seconds
{
    NSUInteger day  = (NSUInteger)seconds/(24*3600);
    NSUInteger hour = (NSUInteger)(seconds%(24*3600))/3600;
    NSUInteger min  = (NSUInteger)(seconds%(3600))/60;
    NSUInteger second = (NSUInteger)(seconds%60);
    NSString *timeStr;
    if (seconds == 0) {
        timeStr = @"已结束";

    }else {
        timeStr = [NSString stringWithFormat:@"%02zd天 %02zd:%02zd:%02zd",(unsigned long)day,(unsigned long)hour,(unsigned long)min,(unsigned long)second];
    }
    return timeStr;
}

//红包页面
- (void)loadHBView:(CGFloat)show{
    
    self.hbview = [[[NSBundle mainBundle] loadNibNamed:@"HBView" owner:nil options:nil] lastObject];
    self.hbview.frame = CGRectMake(0, 0, ScreenWidth, ScreenHeight-49);
    
    MainViewController *main = [[MainViewController alloc]init];
    [main.view addSubview:self.hbview];
    [main.view bringSubviewToFront:self.hbview];
    
}


//自定义导航栏
-(void)showNav:(NSString *)title{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 64)];
    view.backgroundColor = [UIColor whiteColor];
    view.userInteractionEnabled = YES;
    [self.view addSubview:view];
    
    UILabel *lab = [[UILabel alloc] init];
    lab.text = title;
    lab.textColor = [UIColor blackColor];
    lab.font = [UIFont systemFontOfSize:18.0];
    [view addSubview:lab];
    [lab makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(view.centerX);
        make.top.equalTo(34);
    }];
    
    UILabel *line = [[UILabel alloc] init];
    line.backgroundColor = [UIColor lightGrayColor];
    [view addSubview:line];
    [line makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(0);
        make.right.equalTo(0);
        make.bottom.equalTo(view.bottom);
        make.height.equalTo(0.5);
    }];
    
    //返回按钮
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    //btn.backgroundColor = [UIColor redColor];
    [btn setImage:[UIImage imageNamed:@"箭头"] forState:UIControlStateNormal];
    [btn setImage:[UIImage imageNamed:@"箭头"] forState:UIControlStateHighlighted];
    [btn addTarget:self action:@selector(clickBack) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:btn];
    [btn makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(lab.centerY);
        make.left.equalTo(0);
        make.width.equalTo(40);
        make.height.equalTo(40);
    }];
}
// 返回
- (void)clickBack{
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)showAlert:(NSString *)title{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:title preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
    
    [alert addAction:action];
    
    [self presentViewController:alert animated:YES completion:nil];
    
}

//json字符串转日历
-(NSString *)getNewDate:(NSString *)dateStr{
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:[dateStr integerValue]];
    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    [df setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *timeStr = [df stringFromDate:date];
    
    return timeStr;
}
//邮箱验证
-(BOOL)validateEmail:(NSString *)email{
    
    NSString *emailRegex =@"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:email];
}
//身份证验证

- (BOOL)checkIdentityCardNo:(NSString*)cardNo
{
    if (cardNo.length != 18) {
        [SVProgressHUD showErrorWithStatus:@"身份证的位数不够或过多"];
        return  NO;
        
    }
    NSArray* codeArray = [NSArray arrayWithObjects:@"7",@"9",@"10",@"5",@"8",@"4",@"2",@"1",@"6",@"3",@"7",@"9",@"10",@"5",@"8",@"4",@"2", nil];
    
    NSDictionary* checkCodeDic = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@"1",@"0",@"X",@"9",@"8",@"7",@"6",@"5",@"4",@"3",@"2", nil]  forKeys:[NSArray arrayWithObjects:@"0",@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"10", nil]];
    
    NSScanner* scan = [NSScanner scannerWithString:[cardNo substringToIndex:17]];
    
    int val;
    
    BOOL isNum = [scan scanInt:&val] && [scan isAtEnd];
    
    if (!isNum) {
        return NO;
    }
    
    int sumValue = 0;
    
    for (int i =0; i<17; i++) {
        sumValue+=[[cardNo substringWithRange:NSMakeRange(i , 1) ] intValue]* [[codeArray objectAtIndex:i] intValue];
        
    }
    NSString* strlast = [checkCodeDic objectForKey:[NSString stringWithFormat:@"%d",sumValue%11]];
    
    
    
    if ([strlast isEqualToString: [[cardNo substringWithRange:NSMakeRange(17, 1)]uppercaseString]]) {
        return YES;
        
    }
    [SVProgressHUD showErrorWithStatus:@"身份证份证号码错误"];
    
    return  NO;
    
}



- (BOOL)validateIDCardNumber:(NSString *)value
{
    
    value = [value stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    
    int length = 0;
    
    if (!value) {
        return NO;
    }
    else {
        length = (int)value.length;
        
        if (length !=15 && length !=18) {
            return NO;
        }
    }
    // 省份代码
    NSArray *areasArray =@[@"11",@"12", @"13",@"14", @"15",@"21", @"22",@"23", @"31",@"32", @"33",@"34", @"35",@"36", @"37",@"41",@"42",@"43", @"44",@"45", @"46",@"50", @"51",@"52", @"53",@"54", @"61",@"62", @"63",@"64", @"65",@"71", @"81",@"82", @"91"];
    
    NSString *valueStart2 = [value substringToIndex:2];
    
    BOOL areaFlag =NO;
    
    for (NSString *areaCode in areasArray) {
        
        if ([areaCode isEqualToString:valueStart2]) {
            areaFlag =YES;
            break;
        }
    }
    
    if (!areaFlag) {
        return NO;
    }
    
    
    NSRegularExpression *regularExpression;
    NSUInteger numberofMatch;
    int year =0;
    switch (length) {
        case 15:{
            year = [value substringWithRange:NSMakeRange(6,2)].intValue +1900;
            if (year %4 ==0 || (year %100 ==0 && year %4 ==0)) {
                regularExpression = [[NSRegularExpression alloc]initWithPattern:@"^[1-9][0-9]{5}[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}$"
                                                                        options:NSRegularExpressionCaseInsensitive
                                                                          error:nil];//测试出生日期的合法性
            }else {
                regularExpression = [[NSRegularExpression alloc]initWithPattern:@"^[1-9][0-9]{5}[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|1[0-9]|2[0-8]))[0-9]{3}$"
                                                                        options:NSRegularExpressionCaseInsensitive
                                                                          error:nil];//测试出生日期的合法性
            }
            numberofMatch = [regularExpression numberOfMatchesInString:value
                                                               options:NSMatchingReportProgress
                                                                 range:NSMakeRange(0, value.length)];
            
            if(numberofMatch >0) {
                
                return YES;
            }else {
                return NO;
            }
        }
        case 18:
            year = [value substringWithRange:NSMakeRange(6,4)].intValue;
            if (year %4 ==0 || (year %100 ==0 && year %4 ==0)) {
                regularExpression = [[NSRegularExpression alloc]initWithPattern:@"^[1-9][0-9]{5}((19[0-9]{2})|(2[0-9]{3}))((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}[0-9Xx]$"
                                                                        options:NSRegularExpressionCaseInsensitive
                                                                          error:nil];//测试出生日期的合法性
            }else {
                regularExpression = [[NSRegularExpression alloc]initWithPattern:@"^[1-9][0-9]{5}((19[0-9]{2})|(2[0-9]{3}))((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|1[0-9]|2[0-8]))[0-9]{3}[0-9Xx]$"
                                                                        options:NSRegularExpressionCaseInsensitive
                                                                          error:nil];//测试出生日期的合法性
            }
            numberofMatch = [regularExpression numberOfMatchesInString:value
                                                               options:NSMatchingReportProgress
                                                                 range:NSMakeRange(0, value.length)];
            
            if(numberofMatch >0) {
                
                int S = ([value substringWithRange:NSMakeRange(0,1)].intValue + [value substringWithRange:NSMakeRange(10,1)].intValue) *7 + ([value substringWithRange:NSMakeRange(1,1)].intValue + [value substringWithRange:NSMakeRange(11,1)].intValue) *9 + ([value substringWithRange:NSMakeRange(2,1)].intValue + [value substringWithRange:NSMakeRange(12,1)].intValue) *10 + ([value substringWithRange:NSMakeRange(3,1)].intValue + [value substringWithRange:NSMakeRange(13,1)].intValue) *5 + ([value substringWithRange:NSMakeRange(4,1)].intValue + [value substringWithRange:NSMakeRange(14,1)].intValue) *8 + ([value substringWithRange:NSMakeRange(5,1)].intValue + [value substringWithRange:NSMakeRange(15,1)].intValue) *4 + ([value substringWithRange:NSMakeRange(6,1)].intValue + [value substringWithRange:NSMakeRange(16,1)].intValue) *2 + [value substringWithRange:NSMakeRange(7,1)].intValue *1 + [value substringWithRange:NSMakeRange(8,1)].intValue *6 + [value substringWithRange:NSMakeRange(9,1)].intValue *3;
                
                int Y = S %11;
                
                NSString *M =@"F";
                
                NSString *JYM =@"10X98765432";
                
                M = [JYM substringWithRange:NSMakeRange(Y,1)];// 判断校验位
                
                if ([M isEqualToString:[value substringWithRange:NSMakeRange(17,1)]]) {
                    return YES;// 检测ID的校验位
                }else {
                    return NO;
                }
            }else {
                
                return NO;
            }
        default:
            return NO;
    }
}

//手机号验证
- (BOOL)validateMobile:(NSString *)mobile
{
    // 130-139  150-153,155-159  180-189  145,147  170,171,173,176,177,178
    NSString *phoneRegex = @"^((13[0-9])|(15[^4,\\D])|(18[0-9])|(14[57])|(17[013678]))\\d{8}$";
    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];
    return [phoneTest evaluateWithObject:mobile];
}
//6~18位字母与数字组合
-(BOOL)judgePassWordLegal:(NSString *)pass{
    BOOL result = false;
    if ([pass length] >= 6){
        // 判断长度大于8位后再接着判断是否同时包含数字和字符
        NSString * regex = @"^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,16}$";
        NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
        result = [pred evaluateWithObject:pass];
    }
    return result;
}

- (NSString *)getTimeFormat:(NSString *)dateString{
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:[dateString integerValue]];
    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    [df setDateFormat:@"MM-dd hh:mm"];
    NSString *timeStr = [df stringFromDate:date];
    
    return timeStr;
}

- (NSString *)getyYearsTimeFormat:(NSString *)dateString{
//    NSDate *date = [NSDate dateWithTimeIntervalSince1970:[dateString integerValue]];
//    NSDateFormatter *df = [[NSDateFormatter alloc] init];
//    [df setDateFormat:@"YYYY-MM-dd hh:mm"];
//    NSString *timeStr = [df stringFromDate:date];
//    return timeStr;
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:[dateString integerValue]];
    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    [df setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *timeStr = [df stringFromDate: date];
    //    NSString *timeStr = [df stringFromDate:date];
    return timeStr;
}

- (NSString *)getyYearsTimeDayFormat:(NSString *)dateString{
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:[dateString integerValue]];
    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    [df setDateFormat:@"YYYY-MM-dd hh:mm:ss"];
    NSString *timeStr = [df stringFromDate:date];
    return timeStr;
}

- (BOOL) isNullOrEmpty:(NSString *)string
{
    return string == nil
    || [string isEqual: (id)[NSNull null]]
    || [string isKindOfClass:[NSString class]] == NO
    || [@"" isEqualToString:string]
    || [@"<null>" isEqualToString:string]
    || [@"(null)" isEqualToString:string]
    || [[string stringByReplacingOccurrencesOfString:@" " withString:@""] length] == 0U
    || [[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length] == 0U;
}

// 检查摄像头是否支持拍照

- (BOOL)doesCameraSupportTakingPhotos{
    
    return [self cameraSupportsMedia:(NSString *)kUTTypeImage sourceType:UIImagePickerControllerSourceTypeCamera];
    
}
// 判断是否支持某种多媒体类型：拍照，视频

- (BOOL) cameraSupportsMedia:(NSString *)paramMediaType sourceType:(UIImagePickerControllerSourceType)paramSourceType{
    
    __block BOOL result = NO;
    
    if ([paramMediaType length] == 0){
        
        NSLog(@"Media type is empty.");
        
        return NO;
        
    }
    
    NSArray *availableMediaTypes =[UIImagePickerController availableMediaTypesForSourceType:paramSourceType];
    
    [availableMediaTypes enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL*stop) {
        
        NSString *mediaType = (NSString *)obj;
        
        if ([mediaType isEqualToString:paramMediaType]){
            
            result = YES;
            
            *stop= YES;
            
        }
    }];
    
    return result;
    
}

#pragma mark - 相册文件选取相关

// 相册是否可用

- (BOOL) isPhotoLibraryAvailable{
    return [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
